import { useEffect, useState } from "react";
import { useParams } from "react-router-dom"
import request from '../../api/request'
import { Button, Card, Space, List, Avatar, Modal } from "antd";
import { useNavigate } from "react-router-dom";
import { Typography } from 'antd';
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Input } from 'antd';
// import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

import {
    HomeOutlined,
    StepBackwardOutlined,
    UserOutlined,
    SmileOutlined,
    EyeOutlined,
} from '@ant-design/icons';


function Editll() {
    let navtion = useNavigate()
    const { id } = useParams()
    console.log(id);
    const { Title, Text } = Typography;
    const { TextArea } = Input;
    const [arctin, setArctin] = useState<any>()
    const ArtinLit = async () => {
        const res = await request.get(`/article/${id}`)
        console.log(res.data);
        setArctin(res.data)

    }

    useEffect(() => {
        ArtinLit()
    }, [])
    const fh = () => {
        navtion('/')
    }
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null) // TS 语法
    // const [editor, setEditor] = useState(null)                   // JS 语法

    // 编辑器内容
    const [html, setHtml] = useState('<p>hello</p>')

    // 模拟 ajax 请求，异步设置 html
    useEffect(() => {
        setTimeout(() => {
            setHtml('<p>hello world</p>')
        }, 1500)
    }, [])

    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {} // TS 语法
    // const toolbarConfig = { }                        // JS 语法

    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
        // TS 语法
        // const editorConfig = {                         // JS 语法
        placeholder: '请输入内容...',
        maxLength:100,
    }

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

    const [idd, setIdd] = useState()
    const [title, setTitle] = useState()
    const [htmll,setHtmll]=useState('')
    const fs = async () => {
        const hull=html.replace(/傻逼|傻子/g,"**")
        console.log(setHtml);
        
        const res = await request.post('/discuss', {
            userId: 47529555,// 47529555 用户id
            content: hull,//评论内容
            //  commentId:number,//评论ID（非必填，回复评论时使用）
            articleId: id // 文章id 90

        })
        console.log(res);
        ArtinLit()

    }
    const huifu=(e:any)=>{
        setHtmll(e.target.value)
    }

    const hf = (add: any) => {
        setIdd(add.id)
        setIsModalOpen(true)
       setTitle (add.user.username)
    }

    const hfpl=async()=>{
         const res = await request.post('/discuss', {
            userId: 47529555,// 47529555 用户id
            content: htmll,//评论内容
              commentId:idd,//评论ID（非必填，回复评论时使用）
            articleId: id // 文章id 90

        })
        console.log(res);
        ArtinLit()
        setIsModalOpen(false)
        setHtmll('')

    }
    return (
        <div>
            <Button onClick={() => fh()}>返回列表</Button>
            <Card style={{ marginTop: '30px' }}>
                <Title>{arctin?.title}</Title>
                <Space>
                    <Space>
                        <EyeOutlined />
                        <Text>{arctin?.viewCount}</Text>
                    </Space>
                </Space>
            </Card>

            {/* 富文本 */}
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                <Toolbar
                    editor={editor}
                    defaultConfig={toolbarConfig}
                    mode="default"
                    style={{ borderBottom: '1px solid #ccc' }}
                />
                <Editor
                    defaultConfig={editorConfig}
                    value={html}
                    onCreated={setEditor}
                    onChange={(editor) => setHtml(editor.getHtml())}
                    mode="default"
                    style={{ height: '500px', overflowY: 'hidden' }}
                
                />
        
            </div>
            <Button onClick={() => fs()}>发送</Button>
            <Card title={<div>评论 ：{arctin?.comments.length}</div>}>
                {
                    arctin?.comments.length <= 0 ? '暂无数据' : <div>
                        {
                            arctin?.comments.map((item: any) => {
                                const dgxr = (add: any) => {
                                    return (
                                        <List key={add.id} itemLayout='vertical' size='small'>
                                            <List.Item extra={<Button onClick={() => hf(add)}>回复</Button>}>
                                                <List.Item.Meta avatar={<Avatar><UserOutlined /></Avatar>}
                                                    title={<div>{add.user.username}{add.user.createdAt}</div>}
                                                    description={<div><h2>{add.content}</h2></div>}
                                                >

                                                </List.Item.Meta>
                                                {
                                                    add.replies?.length &&
                                                    <List dataSource={add.replies} renderItem={(ww) => dgxr(ww)}></List>
                                                }
                                            </List.Item>
                                        </List>
                                    )
                                }
                                return dgxr(item)
                            })
                        }
                    </div>
                }


            </Card>
             <Modal
        title={`回复${title}的评论`}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       <TextArea rows={4}  value={htmll} onChange={(e)=>huifu(e)}/>
        <Button onClick={()=>hfpl()}>回复</Button>
      </Modal>
        </div>
    )
}

export default Editll
